'use strict';

const { Controller } = require('egg');

class ResultContribution extends Controller {
    /**
* @api {get} /ResultContribution 获取列表
* @apiGroup ResultContribution
*/
    async index() {
        const { ctx, app, config } = this;
        const {
            pageNow = 0,
            pageSize = 10,
            type = 'all'
        } = ctx.query;

        const options = {
            limit: parseInt(pageSize),
            offset: parseInt(pageNow),
            orders: [['id', 'desc']],
            where: {
                type
            }
        };

        let sql_total = `SELECT count(id) FROM ${config.resourceTable.contribution} `;

        if (type === 'all') {
            delete options.where.type;
        } else {
            sql_total += ` WHERE type = '${type}' `;
        }

        const result = await app.mysql.select(config.resourceTable.contribution, options);
        const [{ 'count(id)': totalUserNum }] = await app.mysql.query(sql_total);
        ctx.returnBody(200, `${type || '全部'}稿件列表获取成功`, {
            list: result,
            totalUserNum
        });
    }

    /**
* @api {get} /ResultContribution/:id 获取详情
* @apiGroup ResultContribution
*/
    async show() {
        const { ctx, app, config } = this;
        const { id } = ctx.params;
        const resultInfo = await app.mysql.get(config.resourceTable.contribution, { id });
        const resultFiles = await app.mysql.select(config.baseTable.files, {
            where: {
                used: `contribution_${id}`
            }
        });

        ctx.returnBody(200, '进入了获取详情接口', {
            ...resultInfo,
            listFiles: resultFiles
        });
    }

    /**
* @api {post} /ResultContribution 创建数据
* @apiGroup ResultContribution
*/
    async create() {
        const { ctx, app, config } = this;
        const { user_id } = ctx.token;

        const result = await app.mysql.insert(config.resourceTable.contribution, { user_id });

        ctx.returnBody(200, '新增了一个稿件', { contribution_id: result.insertId });
    }

    /**
* @api {put} /ResultContribution/:id 更改数据
* @apiGroup ResultContribution
*/
    async update() {
        const { ctx, app, config, service } = this;
        const { id } = ctx.params;

        const result = await app.mysql.beginTransactionScope(async conn => {
            const oldData = await conn.get(config.resourceTable.contribution, { id });
            const {
                title = oldData.title,
                type = oldData.type,
                cover = oldData.cover,
                description = oldData.description
            } = ctx.request.body;
            // 如果更换了封面并且有旧封面, 就删掉旧封面, 同时删掉数据库中的
            if (oldData.cover && oldData.cover !== cover) {
                await conn.delete(config.baseTable.files, { link: oldData.cover });
                await service.utilsFilesCos.deleteObject({
                    fileName: oldData.cover,
                    BucketName: 'image'
                });
            }
            const updateRow = {
                title,
                type,
                cover,
                description,
                status: 0
            };
            const resultUpdate = await conn.update(config.resourceTable.contribution, updateRow, { where: { id }});
            return resultUpdate;
        }, ctx);

        ctx.returnBody(200, '修改稿件成功', result);
    }

    /**
* @api {delete} /ResultContribution/:id 删除数据
* @apiGroup ResultContribution
*/
    async destroy() {
        const { ctx, app, config, service } = this;
        const { id } = ctx.params;

        await app.mysql.beginTransactionScope(async conn => {
            // 查询文件数据
            const sqlSelect = `  SELECT link as 'Key' FROM  ${config.baseTable.files} WHERE used = ? `;
            const resultFiles = await conn.query(sqlSelect, [`contribution_${id}`]);
            const cosResult = await service.utilsFilesCos.deleteMultipleObject({
                fileNameArray: resultFiles,
                BucketName: 'video'
            });
            if (cosResult.statusCode !== 200) {
                throw new Error('cos删除出错');
            }
            await conn.delete(config.baseTable.files, { used: `contribution_${id}` });
            await conn.delete(config.resourceTable.contribution, { id });
        }, ctx);

        ctx.returnBody(200, '删除稿件成功');
    }
}

module.exports = ResultContribution;
